package de.preamp.clients.java.utils.ui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import de.preamp.clients.java.utils.AbstractPreferences;
import de.preamp.clients.java.utils.ImageLoader;
import de.preamp.clients.java.utils.Main;
import de.preamp.clients.java.utils.Tools;

/**
 * A dialog used to change the prefernces of the programm.
 * 
 * @author André Stannek
 * @version 2010-03-22
 */
public class PreferencesUI extends JDialog implements ActionListener
{
    /**
     * 
     */
    private static final long serialVersionUID = -418155635454713606L;

    /**
     * 
     */
    private final transient AbstractPreferences preferences;

    /**
     * 
     */
    private final transient JButton browseButton, okButton, saveButton,
	    cancelButton;

    /**
     * 
     */
    private final transient JTextField serverURLText, serverUserText,
	    lastfmUserText, downloadPathText, cacheSize;

    /**
     * 
     */
    private final transient JPasswordField serverPassword, lastfmPassword;

    /**
     * 
     */
    private final transient JCheckBox scroblingEnable, lafEnabled;

    /**
     * @param owner
     *            the owner of this dialog
     */
    public PreferencesUI(final Frame owner)
    {
	super(owner, true);

	preferences = AbstractPreferences.instance();

	serverURLText = new JTextField(preferences.getServerURL());
	serverUserText = new JTextField(preferences.getServerUser());
	lastfmUserText = new JTextField(preferences.getLastfmUser());
	downloadPathText = new JTextField(preferences.getDownloadPath());
	cacheSize = new JTextField(String.valueOf(preferences.getCacheSize()));

	serverPassword =
		new JPasswordField(new String(preferences.getServerPassword()));
	lastfmPassword =
		new JPasswordField(new String(preferences.getLastfmPassword()));

	scroblingEnable =
		new JCheckBox("last.fm scrobbling enabled", preferences
			.isScrobblingEnabled());
	lafEnabled =
		new JCheckBox("system lool & feel enabled", preferences
			.isSystemLAFEnabled());

	browseButton =
		new JButton(new ImageIcon(ImageLoader
			.getImageURL("document-open.png")));

	okButton = new JButton("OK");
	saveButton =
		new JButton("Save", new ImageIcon(ImageLoader
			.getImageURL("media-floppy.png")));
	cancelButton =
		new JButton("Cancel", new ImageIcon(ImageLoader
			.getImageURL("process-stop.png")));

	initUI();
    }

    /**
     * 
     */
    private void initUI()
    {
	this.setResizable(false);
	this.setModal(true);
	final int height = 370;
	final int width = 350;

	this.setLayout(new BorderLayout());
	final JTabbedPane tabPane = new JTabbedPane();

	final GridBagConstraints constraints = new GridBagConstraints();
	constraints.fill = GridBagConstraints.HORIZONTAL;
	constraints.anchor = GridBagConstraints.LINE_START;

	// preamp prefs
	final JPanel preampTab = new JPanel(new GridBagLayout());

	constraints.gridx = 0;
	constraints.gridy = 0;
	preampTab.add(new JLabel("default download folder:",
		SwingConstants.LEFT), constraints);
	constraints.gridy++;
	final JPanel downloadLabel =
		new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
	downloadLabel.setPreferredSize(new Dimension(width - 40, 25));
	downloadLabel.add(downloadPathText);
	browseButton.setPreferredSize(new Dimension(20, 20));
	browseButton.addActionListener(this);
	downloadLabel.add(browseButton);
	downloadPathText.setPreferredSize(new Dimension(downloadLabel
		.getPreferredSize().width
		- browseButton.getPreferredSize().width, 20));
	preampTab.add(downloadLabel, constraints);
	constraints.gridy++;
	preampTab.add(lafEnabled, constraints);

	tabPane.addTab("preamp", null, preampTab, "preamp preferences");

	// server prefs
	final JPanel serverTab = new JPanel(new GridBagLayout());
	serverURLText.setPreferredSize(new Dimension(width - 40, 20));

	constraints.gridx = 0;
	constraints.gridy = 0;
	serverTab.add(new JLabel("preamp server URL:", SwingConstants.LEFT),
		constraints);
	constraints.gridy++;
	serverTab.add(serverURLText, constraints);
	constraints.gridy++;
	serverTab.add(new JLabel(" "), constraints);
	constraints.gridy++;
	serverTab.add(new JLabel("preamp server login:", SwingConstants.LEFT),
		constraints);
	constraints.gridy++;
	serverTab.add(serverUserText, constraints);
	constraints.gridy++;
	serverTab.add(new JLabel(" "), constraints);
	constraints.gridy++;
	serverTab.add(
		new JLabel("preamp server password:", SwingConstants.LEFT),
		constraints);
	constraints.gridy++;
	serverTab.add(serverPassword, constraints);
	constraints.gridy++;
	serverTab.add(new JLabel("playback cache (kB):", SwingConstants.LEFT),
		constraints);
	constraints.gridy++;
	serverTab.add(cacheSize, constraints);

	tabPane.addTab("server", null, serverTab,
		"the preamp server preferences");

	// lastfm prefs

	final JPanel lastfmTab = new JPanel(new GridBagLayout());

	constraints.gridx = 0;
	constraints.gridy = 0;

	scroblingEnable.addChangeListener(new ChangeListener()
	{
	    @Override
	    public void stateChanged(final ChangeEvent event)
	    {
		setLastfmPropsEnable();
	    }
	});
	scroblingEnable.setPreferredSize(new Dimension(width - 40, 20));
	lastfmTab.add(scroblingEnable, constraints);
	constraints.gridy++;
	lastfmTab.add(new JLabel(" "), constraints);
	constraints.gridy++;
	lastfmTab.add(new JLabel("last.fm login:", SwingConstants.LEFT),
		constraints);
	constraints.gridy++;
	lastfmTab.add(lastfmUserText, constraints);
	constraints.gridy++;
	lastfmTab.add(new JLabel(" "), constraints);
	constraints.gridy++;
	lastfmTab.add(new JLabel("last.fm password:", SwingConstants.LEFT),
		constraints);
	constraints.gridy++;
	lastfmTab.add(lastfmPassword, constraints);

	setLastfmPropsEnable();

	tabPane.addTab("last.fm", null, lastfmTab, "Your last.fm user setup");

	this.add(tabPane, BorderLayout.CENTER);

	// buttons

	final JPanel buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT));
	okButton.addActionListener(this);
	cancelButton.addActionListener(this);
	saveButton.addActionListener(this);
	buttons.add(okButton);
	buttons.add(saveButton);
	buttons.add(cancelButton);

	this.add(buttons, BorderLayout.SOUTH);

	this.setBounds(Tools.getCenteredBounds(width, height));
	this.setVisible(true);
    }

    /**
     * 
     */
    private void setLastfmPropsEnable()
    {
	if (scroblingEnable.isSelected())
	{
	    lastfmPassword.setEnabled(true);
	    lastfmUserText.setEnabled(true);
	}
	else
	{
	    lastfmPassword.setEnabled(false);
	    lastfmUserText.setEnabled(false);
	}

    }

    /**
     * saves all preferences to {@link AbstractPreferencese} class.
     * 
     * @throws IOException
     *             if preferences could not be saved
     */
    private void save() throws IOException
    {

	preferences.setServerURL(serverURLText.getText());
	preferences.setLastfmPassword(lastfmPassword.getPassword());
	preferences.setLastfmUser(lastfmUserText.getText());
	preferences.setServerPassword(serverPassword.getPassword());
	preferences.setServerUser(serverUserText.getText());
	preferences.setScrobblingEnabled(scroblingEnable.isSelected());
	preferences.setSystemLAFEnabled(lafEnabled.isSelected());
	preferences.setDownloadPath(downloadPathText.getText());
	try
	{
	    preferences.setCacheSize(Integer.parseInt(cacheSize.getText()));
	}
	catch (final NumberFormatException exception)
	{
	    preferences.setCacheSize(0);
	}

    }

    @Override
    public final void actionPerformed(final ActionEvent event)
    {
	if (event.getSource() == okButton)
	{
	    try
	    {
		this.save();
		this.dispose();
		if (this.getOwner() == null)
		{
		    Main.main(new String[0]);
		}
	    }
	    catch (final IOException e)
	    {
		JOptionPane.showMessageDialog(this,
			"preamp server URL invalid", "invalid URL",
			JOptionPane.ERROR_MESSAGE);
	    }
	}
	else if (event.getSource() == saveButton)
	{
	    try
	    {
		this.save();
	    }
	    catch (final IOException e)
	    {
		JOptionPane.showMessageDialog(this,
			"preamp server URL invalid", "invalid URL",
			JOptionPane.ERROR_MESSAGE);
	    }
	}
	else if (event.getSource() == cancelButton)
	{
	    this.dispose();
	}
	else if (event.getSource() == browseButton)
	{
	    final JFileChooser chooser = new JFileChooser();
	    chooser.setDialogTitle("select default download folder");
	    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
	    chooser.setAcceptAllFileFilterUsed(false);

	    if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
	    {
		downloadPathText.setText(chooser.getSelectedFile().toString());
	    }
	}

    }

}
